package threadPool.ThreadFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadFactoryTest {
    public static void main(String[] args) {
        System.out.println("使用自定义线程池创建类");
        // MyThreadFactory threadFactory = new MyThreadFactory("myThreadFactory",true);
        // 使用线程池创建工厂优雅的实现线程运行异常的捕获
        MyExceptionThreadFactory threadFactory = new MyExceptionThreadFactory("myThreadFactory",true);

        ExecutorService executorService = Executors.newCachedThreadPool(threadFactory);
        for (int i = 0; i < 4; i++) {
            final int index = i;
            /**
             * 这里如果使用 submit() 方法，会导致MyExceptionThreadFactory 中线程异常捕获功能失效
             * 因此必须使用execute() 方法
              */
            executorService.execute(()->{
                if(index == 3){
                    int a = 2/0;
                }
                System.out.println(Thread.currentThread().getName() + " 执行我的线程");
            });
        }
        executorService.shutdown();

        try {
            /**
             * isShutdown用来判断线程池是否已经关闭
             * isTermination 任务全部执行完毕，并且线程池已经关闭，才会返回true
             * awaitTermination 阻塞，直到所有任务在关闭请求后完成执行，或者发生超时时，
             *   或者当前线程中断（以先发生者为准）
             */
            boolean isShutDown = executorService.isShutdown();

            boolean isTermination = executorService.isTerminated();

            boolean isTerminationOk =  executorService.awaitTermination(10, TimeUnit.SECONDS);
            // 判断线程池是否结束的方法
            while(isTerminationOk){
                System.out.println("isTerminationOk = " + isTerminationOk);
                return;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
